<?php
namespace Frame\Libs;

use Admin\Model\UserLogModel;
//定义抽象的基础控制器类
abstract class BaseController
{ 
	//受保护的Smarty对象属性
	protected $smarty = NULL;
	
	//公共的构造方法
	public function __construct()
	{
		//Smarty对象初始化
		$this->initSmarty();
	}

	//私有的Smarty对象初始化方法
	private function initSmarty()
	{
		//创建Smarty对象
		$smarty = new \Frame\Vendor\Smarty();
		//Smarty配置
		$smarty->left_delimiter = "<{";  //定界符
		$smarty->right_delimiter = "}>";
		$smarty->setTemplateDir(VIEW_PATH);//设置视图目录
		$smarty->setCompileDir(sys_get_temp_dir().DS."view".DS);//设置编译目录
		//sys_get_temp_dir() C:\Users\yyf\AppData\Local\Temp
		//给$smarty属性赋值
		$this->smarty = $smarty;
	}
    //权限验证
    protected function denyAccess(){
        //判断用户是否登录
        if(!isset($_SESSION["username"])){
            $this->jump("您还没有登录","?c=User&a=login");
        }
    }
    protected function write_log($code){
    	$data = [
	    	"add_time" => time(),
	    	"user_id"  => $_SESSION["id"],
	    	"code"     => $code,
	    	"ip" 	   => $this->get_ip()
    	];
    	UserLogModel::getInstance()->insert($data);
    }
    protected function get_ip() {
		if(!empty($_SERVER["HTTP_CLIENT_IP"])){
		  $cip = $_SERVER["HTTP_CLIENT_IP"];
		}
		elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
		  $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		}
		elseif(!empty($_SERVER["REMOTE_ADDR"])){
		  $cip = $_SERVER["REMOTE_ADDR"];
		}
		else{
		  $cip = "无法获取！";
		}
		return $cip;
    }
    
	//受保护的跳转方法
	protected function jump($message,$url="?",$time=3)
	{
		$this->smarty->assign("message",$message);
        $this->smarty->assign("url",$url);
        $this->smarty->assign("time",$time);
        $this->smarty->display("Public/jump.html");
        die();
	}
	protected function ajax_return($array){
		header("content:application/json;chartset=uft-8");
		die(json_encode($array));
	}
    protected function filter($val)
    {
        //xss漏洞防范方法
        require_once (FRAME_PATH."Vendor".DS."purifier".DS."HTMLPurifier.auto.php");
        require_once (FRAME_PATH."Vendor".DS."purifier".DS."HTMLPurifier.func.php");

        $dirty_html = isset($val)?$val:false;
        $html = HTMLPurifier($dirty_html);
        return $html;
    }

}